package com.xxg.renrenlogin.manager.jiguang;

import com.alibaba.fastjson.JSON;
import com.xxg.renrenlogin.exception.ErrorMessage;
import com.xxg.renrenlogin.exception.JiGuangException;
import com.xxg.renrenlogin.manager.jiguang.query.JiGuangCheckCodeQuery;
import com.xxg.renrenlogin.manager.jiguang.query.JiGuangGetCodeQuery;
import com.xxg.renrenlogin.manager.jiguang.query.JiGuangLoginTokenQuery;
import com.xxg.renrenlogin.manager.jiguang.query.JiGuangOpenQuery;
import com.xxg.renrenlogin.manager.jiguang.result.JiGuangCheckCodeResult;
import com.xxg.renrenlogin.manager.jiguang.result.JiGuangGetCodeResult;
import com.xxg.renrenlogin.manager.jiguang.result.JiGuangOpenResult;
import com.xxg.renrenlogin.manager.jiguang.result.JiGuangVerifyResult;
import com.xxg.renrenlogin.util.RSAUtil;
import com.xxg.renrenlogin.util.RestServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Base64;

/**
 * 极光服务接口
 *
 * @author xxg
 * @date 2020-09-25
 */
@Component
public class JiGuangManager {
    private static final Logger logger = LoggerFactory.getLogger(JiGuangManager.class);

    @Value(value = "${jiguang.smsUrl}")
    private String jiGuangSmsUrl;
    @Value(value = "${jiguang.apiUrl}")
    private String jiGuangApiUrl;
    @Value(value = "${jiguang.appKey}")
    private String jiGuangAppKey;
    @Value(value = "${jiguang.masterSecret}")
    private String jiGuangMasterSecret;

    private String authorization;

    private String getAuthorization() {
        if (authorization == null) {
            String key = jiGuangAppKey + ":" + jiGuangMasterSecret;
            authorization = "Basic " + Base64.getEncoder().encodeToString(key.getBytes());
        }
        return authorization;
    }

    /**
     * 极光token认证
     *
     * @param loginToken 令牌
     * @return 手机号码
     * @throws JiGuangException 异常信息
     */
    public String loginTokenVerify(JiGuangLoginTokenQuery loginToken) throws JiGuangException {
        String serviceUrl = jiGuangApiUrl + "loginTokenVerify";
        JiGuangVerifyResult result;
        try {
            result = RestServiceUtil.remotePostCall(serviceUrl, loginToken, getAuthorization(), JiGuangVerifyResult.class);
        } catch (Exception e) {
            logger.error(ErrorMessage.JIGUANG_ERROR + "\n接口:"
                    + serviceUrl + "\n参数:" + JSON.toJSONString(loginToken) + "\n错误信息:" + e.getMessage(), e);
            throw new JiGuangException(ErrorMessage.JIGUANG_ERROR);
        }
        // 返回成功代码
        int code = 8000;
        if (result.getCode().equals(code)) {
            try {
                return RSAUtil.decrypt(result.getPhone(), RSAUtil.PRI_KEY);
            } catch (Exception e) {
                logger.error(ErrorMessage.JIGUANG_DECRYPT_ERROR + "\n接口:"
                        + serviceUrl + "\n参数:" + JSON.toJSONString(loginToken) +
                        "\n结果:" + JSON.toJSONString(result) + "\n错误信息:" + e.getMessage(), e);
                throw new JiGuangException(ErrorMessage.JIGUANG_DECRYPT_ERROR);
            }
        } else {
            logger.error(ErrorMessage.JIGUANG_RESULT_ERROR + "\n接口:"
                    + serviceUrl + "\n参数:" + JSON.toJSONString(loginToken) + "\n结果:" + JSON.toJSONString(result));
            throw new JiGuangException(ErrorMessage.JIGUANG_RESULT_ERROR);
        }
    }

    /**
     * 查询极光认证是否开通情况
     *
     * @return 开通结果
     * @throws JiGuangException 异常信息
     */
    public String query() throws JiGuangException {
        String serviceUrl = "https://admin.verification.jpush.cn/v1/admin/query";
        JiGuangOpenQuery jiGuangOpenQuery = new JiGuangOpenQuery("ca537f9d0e56cf1134458e51", "a");
        JiGuangOpenResult result;
        try {
            result = RestServiceUtil.remotePostCall(serviceUrl, jiGuangOpenQuery, authorization, JiGuangOpenResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        System.out.println(JSON.toJSONString(result));
        return JSON.toJSONString(result);
    }

    /**
     * 发送验证码
     *
     * @param jiGuangGetCodeQuery 手机号码
     * @return 验证码ID
     * @throws JiGuangException 异常信息
     */
    public String getCode(JiGuangGetCodeQuery jiGuangGetCodeQuery) throws JiGuangException {
        String serviceUrl = jiGuangSmsUrl + "codes";
        JiGuangGetCodeResult result;
        try {
            result = RestServiceUtil.remotePostCall(serviceUrl, jiGuangGetCodeQuery,
                    getAuthorization(), JiGuangGetCodeResult.class);
        } catch (Exception e) {
            logger.error(ErrorMessage.JIGUANG_ERROR + "\n接口:" + serviceUrl
                    + "\n参数:" + JSON.toJSONString(jiGuangGetCodeQuery) + "\n错误信息:" + e.getMessage(), e);
            throw new JiGuangException(ErrorMessage.JIGUANG_ERROR);
        }
        if (result.getMsg_id() == null) {
            logger.error(ErrorMessage.JIGUANG_RESULT_ERROR + "\n接口:" + serviceUrl
                    + "\n参数:" + JSON.toJSONString(jiGuangGetCodeQuery) + "\n错误信息:" + JSON.toJSONString(result));
            throw new JiGuangException(ErrorMessage.JIGUANG_RESULT_ERROR);
        }
        return result.getMsg_id();
    }

    /**
     * 验证验证码
     *
     * @param msgId                 验证码ID
     * @param jiGuangCheckCodeQuery 验证码
     * @return true-验证通过，false-验证不通过
     * @throws JiGuangException 异常信息
     */
    public boolean checkCode(String msgId, JiGuangCheckCodeQuery jiGuangCheckCodeQuery) throws JiGuangException {
        String serviceUrl = jiGuangSmsUrl + "codes/" + msgId + "/valid ";
        JiGuangCheckCodeResult result;
        try {
            result = RestServiceUtil.remotePostCall(serviceUrl, jiGuangCheckCodeQuery,
                    getAuthorization(), JiGuangCheckCodeResult.class);
        } catch (Exception e) {
            logger.error(ErrorMessage.JIGUANG_ERROR + "\n接口:" + serviceUrl
                    + "\n参数:" + JSON.toJSONString(jiGuangCheckCodeQuery) + "\n错误信息:" + e.getMessage(), e);
            throw new JiGuangException(ErrorMessage.JIGUANG_ERROR);
        }
        if (!result.is_valid()) {
            logger.error(ErrorMessage.JIGUANG_RESULT_ERROR + "\n接口:" + serviceUrl
                    + "\n参数:" + JSON.toJSONString(jiGuangCheckCodeQuery) + "\n错误信息:" + JSON.toJSONString(result));
            throw new JiGuangException(ErrorMessage.JIGUANG_RESULT_ERROR);
        }
        return result.is_valid();
    }
}
